<!--奖金测算-人员测算-人员测算配置-->
<template>
  <basic-container class="bonus">
    <flexible :leftCols="leftCols" :removeHeight="100" ref="flexibleRef">
      <template slot="left">
       <!--左侧机构树组件-->
       <org-tree-by-dept ref="orgTreeByDept" @sendCurrentOrg="getCurrentOrg"></org-tree-by-dept>
      </template>
      <template slot="right">
        <div class="search-form">
          <el-form :inline="true" :model="searchForm" >
            <el-form-item label="姓名">
              <el-input v-model="searchForm.personName" placeholder="姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="员工编号">
              <el-input v-model="searchForm.personCode" placeholder="员工编号" clearable></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button type="primary" @click="handleSearch" :disabled="currentOrg == ''">查询</el-button>
          </div>
        </div>
        <div class="mb10">
          <el-button type="primary" @click="addUser" :disabled="currentOrg == ''" v-if="moudelType != 'xs'">新增</el-button>
          <el-button type="danger" plain @click="delUser(true)" :disabled="currentOrg==''" v-if="moudelType != 'xs'">删除</el-button>
          <el-button type="primary" plain @click="downLoad" :disabled="currentOrg==''">下载模板</el-button>
          <el-upload
            action='/bonus/bonusperson/importRatio'
            accept=".xlsx, .xls"
            :headers="headers"
            class="upload-demo inline-block"
            :before-upload="beforeAvatarUpload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            :data="importData">
            <el-button  size="small" class="ml10"  type="primary" plain :disabled="currentOrg==''">导入</el-button>
          </el-upload>
        </div>
        <el-table
          v-loading="tableLoadingUser"
          :data="tableDataUser"
          ref="tableRef"
          @selection-change="handleSelectionChange"
          height="calc(100vh - 290px)"
          border
          :cell-class-name="rowSpan3"
          :row-key="getRowKeys"
          style="width: 100%">
          <el-table-column
            type="selection"
            align="center"
            :reserve-selection='true'
            width="55">
          </el-table-column> <!--:reserve-selection='true' 配合row-key可实现跨区勾选-->
          <el-table-column width="55" label="序号" align="center" header-align="center">
            <template slot-scope="scope">
              {{(page.currentPage - 1) * page.pageSize + scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column
            prop="personCode"
            label="员工编号"
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="personName"
            label="姓名"
            show-overflow-tooltip
            min-width="100">
          </el-table-column>
          <el-table-column
            prop="post"
            min-width="120"
            show-overflow-tooltip
            label="岗位/职级">
          </el-table-column>
          <el-table-column
            prop="postRatio"
            min-width="100"
            header-align="center"
            align="center"

            label="岗位系数"
            v-if=" moudelType == 'xs'">
             <template slot-scope="scope">
                <div class="inner-row">
                   <div class="col">
                     <span>一级</span>
                     <span>{{scope.row.postRatioOne}}</span>
                   </div>
                   <div class="col">
                     <span>二级</span>
                     <span>{{scope.row.postRatioTwo}}</span>
                   </div>
                   <div class="col">
                     <span>三级</span>
                     <span>{{scope.row.postRatioThree}}</span>
                   </div>
                </div>
             </template>
          </el-table-column>
          <el-table-column
            prop="leaderFlag"
            label="是否是直管领导"
            align="center"
            width="140"
            v-if="moudelType != 'xs'">
            <template slot-scope="scope">
              <span>{{scope.row.leaderFlag == '0' ? '否' : scope.row.leaderFlag == '1' ? '是' : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="eccFlag"
            label="是否回传ECC"
            align="center"
            width="140"  v-if="moudelType != 'xs'">>
            <template slot-scope="scope">
              <span>{{scope.row.eccFlag == '0'? '否' : scope.row.eccFlag == '1' ? '是' : ''}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" width="120px" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="text"  class="delete_btn" @click="delUser(false,scope.row)"  v-if="moudelType != 'xs'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="avue-crud__pagination">
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="page.currentPage"
            :page-sizes="[2,10, 20, 50, 100]"
            :page-size="page.pageSize"
            :total="page.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </div>
      </template>
    </flexible>

    <!--添加人员-->
    <user-form ref="userFormRef" :moudelType="moudelType" @refresh="refreshUserTable"></user-form>
  </basic-container>
</template>

<script>
import flexible from "@/views/bonusmanage/components/flexible";
import userForm from "@/views/bonusmanage/basic/user/userForm";
import {getUserOfDeptById,delBatch,exportExcel} from '@/api/bonus/calculateuserconfig'
import orgTreeByDept from "@/views/bonusmanage/components/orgTreeByDept";
import store from "@/store";
export default {
  name: "index",
  props:{
     moudelType:{
       type:String,
       default:''
     },
     leftCols:{
       type:Number,
       default: 6
     }
  },
  components:{
    orgTreeByDept,
    userForm,
    flexible
  },
  watch: {

  },
  computed: {

  },
  data(){
    return{
      tableLoadingUser:false,
      // leftCols:6,
      tableData:[],
      searchForm: {},
      multipleSelection:[],
      page:{
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      tableDataUser: [],
      currentOrg:'',
      //---------------导入导出-------------
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
      importData: {
        jjDeptId: undefined
      }
    }
  },
  created(){
    this.$nextTick(()=>{
      this.$refs.orgTreeByDept.getJiangJinJg() ;
    })
  },
  mounted() {

  },
  methods: {
    handleSelectionChange(list){
      this.multipleSelection = list ;
      this.ids = this.multipleSelection.map((ele) => {
        return ele.id
      })
    },
    handleSearch(){
      this.page.currentPage = 1;
      this.onLoad() ;
    },
    refreshUserTable(){
      this.onLoad() ;
    },
    getCurrentOrg(item){
      this.currentOrg = item //当前点击的机构
      this.importData.jjDeptId = item.bonusDeptId //导入用的参数
      this.onLoad() ;
    },
    addUser(){
      if (!this.currentOrg){
        this.$message.error('请选择机构')
        return
      }
       this.$refs.userFormRef.init('add',{},this.currentOrg)
    },
    //删除
    delUser(batch,item){
      let msg = '' ;
      let ids = ''
      if (batch){ //批量
        msg = '确定删除选中的数据吗?'
        if (this.multipleSelection.length == 0){
          this.$message.error('请勾选要删除的数据')
          return ;
        }
        ids = this.ids.toString() ;
      }else{ //单条
        msg = '确定删除此条数据吗?'
        ids = item.id ;
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoadingUser = true ;
        delBatch({ids:ids}).then(res=>{
          this.$message.success('操作成功')
          this.onLoad();
        }).catch(()=>{
          this.tableLoadingUser = false ;
        })
      }).catch(() => {

      });
    },
    //编辑
    editUser(item){
      this.$refs.userFormRef.init('edit',JSON.parse(JSON.stringify(item)),this.currentOrg)
    },
    onLoad(){
      this.tableLoadingUser = true ;
      getUserOfDeptById(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      },{DeptBaseId:this.currentOrg.id},this.searchForm)).then(res=>{
        if (res.data.code == 0){
          this.tableDataUser = res.data.data.records
          this.page.total = res.data.data.total ;
          this.page.currentPage = res.data.data.current ;
        }else{
          this.$message.error(res.data.msg)
        }
        this.tableLoadingUser = false ;
      }).catch(()=>{
        this.tableLoadingUser = false ;
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      this.onLoad() ;
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.currentPage = val;
      this.onLoad() ;
    },
    rowSpan3({row, column, rowIndex, columnIndex}){
      if (column.property == "postRatio"){
        return 'rowSpan3'
      }
    },
    /**
     * 从静态地址汇总下载模板静态文件，复杂情况不能使用这种方式
     */
    downLoad(){

      let data = this.$refs.tableRef.selection;
      if (data.length == 0) {
        this.$message.error("请勾选要下载的数据！");
        return;
      }

      let filename = "人员测算配置" + ".xlsx";
      let ids = [];
      for (let i = 0; i < data.length; i++) {
        ids.push(data[i].id);
      }
      this.tableLoadingUser = true ;
      exportExcel({
        ids: ids,
      }).then((response) => {
        this.$message.success("导出成功!");
        let url = window.URL.createObjectURL(new Blob([response.data]));
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        link.click();
        this.tableLoadingUser = false ;
      }).catch(err=>{
        this.tableLoadingUser = false ;
      });
    },
//--------------------导入导出------------
    /**
     * 文件上传前
     */
    beforeAvatarUpload(file) {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    /**
     * 文件上传成功到pigx的统计文件管理后转发
     */
    handleUploadSuccess(response, file, fileList) {
      this.loading.close()
      if (response.data) {//如果解析数据中由特殊情况，向前台返回1，有错误数据返回2
        if (response.data == 2) {
          this.$message.error(response.msg)
        } else {
          this.$message.warning(response.msg)
        }
      } else {
        this.getCurrentOrg(this.currentOrg)
        this.$message.success(response.msg)
      }
    },
    handleUploadError(response, file, fileList) {
      this.loading.close()
      this.$message.error('上传出错：' + response.message)
    },
    getRowKeys(row){
      return row.id
    }
  }
}
</script>

<style >

</style>
